﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Runtime;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace utils.webtime
{
    class GetTimeManager
    {
      
        #region 获取网络时间
        ///<summary>
        /// 获取标准北京时间2
        ///</summary>
        ///<returns></returns>
        public static DateTime GeSuNingTime()
        {
            DateTime dt;
            WebRequest wrt = null;
            WebResponse wrp = null;
            try
            {
                wrt = WebRequest.Create("http://quan.suning.com/getSysTime.do");
                if (null == wrt)
                {
                    return DateTime.Parse("2050-1-1");
                }
                wrp = wrt.GetResponse();

                string html = string.Empty;
                using (Stream stream = wrp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        html = sr.ReadToEnd();
                    }
                }
                if(html!=string.Empty)
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(html);
                    string sysTime2 = jo["sysTime2"].ToString();
                    dt = DateTime.Parse(sysTime2);
                    if (wrp != null)
                        wrp.Close();
                    if (wrt != null)
                        wrt.Abort();
                    return dt;
                }
               
                //  MessageBox.Show(year + "-" + month + "-" + day + "" + hour + ":" + minite + ":" + second);
               
            }
            catch (WebException e)
            {
                // MessageBox.Show("WebException:" + e.ToString());
                //System.DateTime currentTime = System.DateTime.Now;
                //return  currentTime;
               // return DateTime.Parse("2050-1-1");
            }
            catch (Exception e)
            {
                //  MessageBox.Show("Exception:" + e.ToString());
                //System.DateTime currentTime = System.DateTime.Now;
                //return currentTime;
               // return DateTime.Parse("2050-1-1");
            }
            finally
            {
                if (wrp != null)
                    wrp.Close();
                if (wrt != null)
                    wrt.Abort();
            }
            return  DateTime.Parse("2050-1-1"); ;
        }

        private static int GetInt(string origin, bool fullMatch)
        {
            if (string.IsNullOrEmpty(origin))
            {
                return 0;
            }
            origin = origin.Trim();
            if (!fullMatch)
            {
                string pat = @"-?\d+";
                Regex reg = new Regex(pat);
                origin = reg.Match(origin.Trim()).Value;
            }
            int res = 0;
            int.TryParse(origin, out res);
            return res;
        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        public  static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            string mytime = timeStamp;
            if(timeStamp.Length==13)
            {
                mytime = timeStamp + "0000";
            }
            else if(timeStamp.Length==10)
            {
                mytime = timeStamp + "0000000";
            }
            long lTime = long.Parse(mytime);
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        //http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp

        public static DateTime GetTaoBaoTimeStamp()
        {
            DateTime dt;
            WebRequest wrt = null;
            WebResponse wrp = null;
            try
            {
                wrt = WebRequest.Create("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp");
                if (null == wrt)
                {
                    return DateTime.Parse("2050-1-1");
                }
                wrp = wrt.GetResponse();

                string html = string.Empty;
                
                using (Stream stream = wrp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        html = sr.ReadToEnd();
                    }
                }
                if (html != string.Empty)
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(html);
                    string sysTime2 = jo["data"]["t"].ToString();
                    if (wrp != null)
                        wrp.Close();
                    if (wrt != null)
                        wrt.Abort();
                    return GetTime(sysTime2);
                }
                else
                {
                   
                }
                //  MessageBox.Show(year + "-" + month + "-" + day + "" + hour + ":" + minite + ":" + second);

            }
            catch (WebException e)
            {
                 MessageBox.Show("WebException:" + e.ToString());
                //System.DateTime currentTime = System.DateTime.Now;
                //return  currentTime;
                
            }
            catch (Exception e)
            {
                  MessageBox.Show("Exception:" + e.ToString());
                //System.DateTime currentTime = System.DateTime.Now;
                //return currentTime;
               
            }
            finally
            {
                if (wrp != null)
                    wrp.Close();
                if (wrt != null)
                    wrt.Abort();
            }
            return DateTime.Parse("2050-1-1");
        }


        /*
        public static  DateTime GetNowTime()
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = "http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=2",
                Method = "GET",
            };
            HttpResult R = http.GetHtml(item);
            Regex regex = new Regex(@"0=(?<timestamp>\d{10})\d+");
            Match match = regex.Match(R.Html);
            if (match.Success)
            {
                return GetTime(match.Groups["timestamp"].Value);
            }
            return  DateTime.Parse("2050-1-1");
        }*/

        /// <summary>
        /// http://shijian.duoshitong.com/time.php
        /// </summary>
        /// <returns></returns>
        public static DateTime getNowTime002()
        {

            DateTime oritime = DateTime.Parse("2050-1-1");
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                string lret = wc.DownloadString("http://shijian.duoshitong.com/time.php");
                String[] tts = lret.Split(new char[] { '\r', '\n' });
                if (null != tts && tts.Length > 0)
                {
                    foreach (String line in tts)
                    {
                        //System.Windows.Forms.MessageBox.Show(line);
                        if (line.StartsWith("var") && line.Contains("timeDiff") && line.Contains("-"))
                        {
                            String[] times = line.Split(new char[] { '-' });
                            if (null != times && times.Length == 2)
                            {
                                //System.Windows.Forms.MessageBox.Show(times[1]);
                                String timeSpan = times[1].Trim();
                                if (timeSpan.EndsWith(";"))
                                {
                                    timeSpan = timeSpan.Substring(0, 10);
                                }
                                oritime = GetTime(timeSpan);
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                return DateTime.Parse("2050-1-1");
            }
            return oritime;
        }


        public static DateTime getBaidTime()
        {
            DateTime oritime = DateTime.Parse("2050-1-1");
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                string lret = wc.DownloadString("http://open.baidu.com/special/time/");
                System.Text.RegularExpressions.Match mc = System.Text.RegularExpressions.Regex.Match(lret, @"window.baidu_time\(([0-9]{13})\);");
                string sdt = mc.Value.Substring(18);
                sdt = sdt.Substring(0, sdt.Length - 2);
                long ldt = Convert.ToInt64(sdt) / 1000;
                oritime = Convert.ToDateTime("1970-1-1 0:0:0");
                oritime = oritime.AddSeconds(ldt).AddHours(8);
            }
            catch (Exception ee)
            {
                return DateTime.Parse("2050-1-1");
            }
            return oritime;
        }
        #endregion
    }
}
